﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing.Impl.v0_9_1;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Broker.Upstream.Properties;

namespace Broker.Upstream
{
    public class NotificationService : INotificationService
    {
        public void UpdateStock(Model.Stock stock)
        {
            Console.WriteLine("Updating stock '{0}'.", stock.Name);
            try
            {
                this.Notify(stock);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("An error occurred during updating stock.");
            }
        }

        private void Notify(object obj)
        {
            ConnectionFactory factory = new ConnectionFactory();
            factory.Uri = Settings.Default.ServerAddress;
            using (IConnection connection = factory.CreateConnection())
            {
                using (IModel model = connection.CreateModel())
                {
                    model.ExchangeDeclare(Settings.Default.ExchangeName, ExchangeType.Fanout, true);
                    String queueName = String.Format("{0}-queue", Settings.Default.ExchangeName);
                    model.QueueDeclare(queueName, true, false, false, null);
                    model.QueueBind(queueName, Settings.Default.ExchangeName, String.Empty);

                    MemoryStream memStream = new MemoryStream();
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(memStream, obj);
                    byte[] objectBytes = memStream.ToArray();
                    model.BasicPublish(Settings.Default.ExchangeName, String.Empty, null, objectBytes);
                }
            }
        }

    }
}
